package pt.ua.helpdesk.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import persistence.Administrator;
import persistence.Command;
import persistence.Comment;
import persistence.Person;
import persistence.Ticket;
import persistence.Utilizador;
import pt.ua.helpdesk.client.ServiceLogin;
import pt.ua.helpdesk.global.Global;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.jscape.inet.util.MD5;

public class ServiceLoginImpl extends RemoteServiceServlet implements ServiceLogin {
	private static final long serialVersionUID = 1L;

	@Override
    public ArrayList loginCheck(String username, String pass) {
		MD5 md5 = new MD5(pass);

        // ArrayList a ser retornado
        ArrayList<Object> ret = null;

        //Parametros da query
        ArrayList<Object> par = new ArrayList<Object>();
        par.add(username);
        par.add(md5.toString());
        par.add((short)1);
        List<Person> l = (List<Person>)Command.select("select p from Person p where (p.username LIKE ?1) AND (p.password LIKE ?2) AND (p.active = ?3)", par);
        
        if (l.size() != 0) {            
            Person p = (Person) l.get(0);
            ret = new ArrayList<Object>();
            ret.add(p.getIdperson());
            ret.add(p.getUsername());
            
            if(p.getPersonType().equals("Utilizador"))
            {
            	ret.add(new Integer(1));
            }
            else if (p.getPersonType().equals("Assistente"))
            {
            	ret.add(new Integer(2));
            }
            else if (p.getPersonType().equals("Administrador"))
            {
                    List<Administrator> l3 = (List<Administrator>)Command.select("select a from Administrator a where (a.username LIKE ?1) AND (a.password LIKE ?2) AND (a.active = ?3)", par);
                    if(l3.size() != 0)
                    {
                    	Administrator a = (Administrator)l3.get(0);
                    	if(a.getLevel() == (short)1)
                    		ret.add(new Integer(3));
                    	else
                    		ret.add(new Integer(4));
                    }              
            }
            return ret;
        } else {
            return null;
        }
        
    }

    @Override
    public String registar(String username, String pass, String Email, String name) {

    	String ret = "";
    	
    	// Verificar dados unique
        //Parametros da query
        ArrayList<String> par = new ArrayList<String>();
        par.add(Email);
        par.add(username);
    	
    	List<Utilizador> l = (List<Utilizador>)Command.select("select u from Utilizador u where (u.email LIKE ?1) OR (u.username LIKE ?2)", par);
    	
    	if (l.size() != 0) {
    		Utilizador u = l.get(0);
    		if(u.getEmail().equals(Email))
    			ret = "1";
    		if (u.getUsername().equals(username))
    			ret += "2";
    	}
    	else
    	{
	    	long code = Global.generateCode(10000000, 99999999);
	        MD5 md5 = new MD5(pass);       
	        Date now = new Date();
	        //DateFormat df = DateFormat.getInstance().format(now);
	        //Person p = new Person(name, username,pass, Email, now );
	        
	        Utilizador u = new Utilizador();
	        u.setActive((short)1);
	        u.setCode((int)code);
	        u.setDate(now);
	        u.setEmail(Email);
	        u.setName(name);
	        u.setPassword(md5.toString());
	        u.setPersonType("Utilizador");
	        u.setUsername(username);
	        u.setValid((short)0);
	        u.setCommentCollection(new ArrayList<Comment>());
	        u.setTicketCollection(new ArrayList<Ticket>());
	        
	        boolean flag = false;
	        
	        flag = Command.set(u);
	        if(flag)
	        {
	            String body = "";
	            body = "Boas, <br>";
	            body += "Registaste-te com sucesso no AAUAv's Helpdesk. <br>";
	            body += "Agora ter�s de activar a tua conta, para isso acede ao site e vai ao link \"Activar Conta\". De seguida introduz os seguintes dados: <br>";
	            body += "&nbsp;&nbsp;&nbsp;&nbsp;<b>E-mail:</b> " + Email + " <br>";
	            body += "&nbsp;&nbsp;&nbsp;&nbsp;<b>C�digo de Activa��o:</b> " + code + " <br><br>";
	            body += "Obrigado.";
	
	            Global.sendEmail(Email, "AAUAv's Helpdesk - Novo Registo", body);
	        	ret = "";
	        }
	        else
	        	ret = "9";
    	}
    	return ret;
               
    }

    @Override
    public Boolean activar(String email, long codigo) {
        boolean ret = false;
        
     // Verificar dados unique
        //Parametros da query
        ArrayList<Object> par = new ArrayList<Object>();
        par.add(email);
        par.add(codigo);
        
    	
    	List<Utilizador> l = (List<Utilizador>)Command.select("select u from Utilizador u where (u.email LIKE ?1) AND (u.code = ?2)", par);
    	if(l.size() != 0)
    	{
    		Utilizador u = l.get(0);
    		//Verificar se a conta j� est� validada ou activa
    		if((u.getValid() == (short)1) || (u.getActive() == (short)0))
    			ret = false;
    		else
    		{
    			u.setValid((short)1);
    			ret = Command.update(u);
    		}
    	}
        
    	return ret;
    }

    @Override
    public Boolean novapass(String email) {
        boolean ret = false;
        
        // Verificar dados unique
        //Parametros da query
       ArrayList<String> par = new ArrayList<String>();
       par.add(email);           
       	
       	List<Utilizador> l = (List<Utilizador>)Command.select("select u from Utilizador u where (u.email LIKE ?1)", par);
       	if(l.size() != 0)
       	{
       		Utilizador u = l.get(0);
       		//Verificar se a conta j� est� validada ou activa
       		if((u.getValid() == (short)0) || (u.getActive() == (short)0))
       			ret = false;
       		else
       		{
       			long pass = Global.generateCode(10000000, 99999999);
                MD5 md5 = new MD5(String.valueOf(pass));
                
       			u.setPassword(md5.toString());
       			ret = Command.update(u);
       			
       			if(ret)
       			{
       	            String body = "";
       	            body = "Boas, <br>";
       	            body += "Foi gerada uma nova Palavra-chave. <br>";
       	            body += "&nbsp;&nbsp;&nbsp;&nbsp;<b>Palavra-Chave:</b> " + pass + " <br><br>";
       	            body += "Obrigado.";

       	            Global.sendEmail(email, "AAUAv's Helpdesk - Nova Palavra-Chave", body);
       			}
       		}
       	}
           
       	return ret;
    }

    @Override
    public Boolean editaccount(String username, String pass, String pass2) {
    	boolean ret = false;
        //Parametros da query
    	MD5 md51 = new MD5(String.valueOf(pass2));
    	
    	ArrayList<String> par = new ArrayList<String>();
        par.add(username);
        par.add(md51.toString());
       	
       	List<Person> l = (List<Person>)Command.select("select p from Person p where (p.username LIKE ?1) AND (p.password LIKE ?2)", par);
       	if(l.size() != 0)
       	{
       		Person p = l.get(0);
       		MD5 md5 = new MD5(pass);
       		p.setPassword(md5.toString());
			ret = Command.update(p);
       	}
    	return ret;
    }

}
